<template>
  <j-modal
    :title="$t('结账单')"
    :width="width"
    :visible="visible"
    switchFullscreen
    :okButtonProps="{ class: { 'jee-hidden': disableSubmit } }"
    @cancel="handleCancel"
  >
    <template slot="footer">
      <a-button v-has="'BisCheckOutController:print'" type="primary" @click="printReport">{{$t('打印')}}</a-button>
      <a-button v-has="'BisCheckOutController:export'" type="primary" @click="handleExportXls($t('结账单'))">{{$t('导出')}}</a-button>
      <a-button @click="handleCancel">{{$t('关闭')}}</a-button>
    </template>
    <div>
      <a-row :gutter="[10, 20]">
        <a-col :span="8" :offset="1">
          <div>{{$t('结账单号')}}：{{ model.id }}</div>
        </a-col>
        <a-col :span="10">
          <div>{{$t('账目开始时间')}}：{{ model.startTime }}</div>
        </a-col>
      </a-row>
      <a-row :gutter="[10, 20]">
        <a-col :span="8" :offset="1">
          <div>{{$t('设备')}}：{{ model.deviceName }}（{{ model.deviceId }}）</div>
        </a-col>
        <a-col :span="10">
          <div>{{$t('操作员')}}：{{ model.operator }}</div>
        </a-col>
      </a-row>
      <a-row :gutter="[10, 20]">
        <a-col :span="8" :offset="1">
          <div>{{$t('结账人')}}：{{ model.createBy }}</div>
        </a-col>
        <a-col :span="10">
          <div>{{$t('结账时间')}}：{{ model.createTime }}</div>
        </a-col>
      </a-row>
      <a-row :gutter="[0, 30]">
        <a-col>
          <ul>
            <li style="font-weight: bold">{{$t('收款明细')}}</li>
          </ul>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="22" :offset="1">
          <a-table :columns="columns4" :dataSource="dataSource4" :pagination="false" bordered>
            <template slot="payType_dictText" slot-scope="text, record">
              <span v-if="text == $t('合计')">{{ text }}</span>
              <a v-else @click="viewPayDetail(record)">{{ text }}</a>
            </template>
          </a-table>
        </a-col>
      </a-row>
      <!-- <a-row :gutter="[0, 30]">
        <a-col>
          <ul>
            <li style="font-weight: bold">商品销售明细</li>
          </ul>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="22" :offset="1">
          <a-table :columns="columns1" :dataSource="dataSource1" :pagination="false" bordered></a-table>
        </a-col>
      </a-row>
      <a-row :gutter="[0, 30]">
        <a-col>
          <ul>
            <li style="font-weight: bold">商品形态明细</li>
          </ul>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="22" :offset="1">
          <a-table :columns="columns2" :dataSource="dataSource2" :pagination="false" bordered></a-table>
        </a-col>
      </a-row>
      <a-row :gutter="[0, 30]">
        <a-col>
          <ul>
            <li style="font-weight: bold">商品兑换明细</li>
          </ul>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="22" :offset="1">
          <a-table :columns="columns3" :dataSource="dataSource3" :pagination="false" bordered></a-table>
        </a-col>
      </a-row> -->
      <a-row :gutter="[0, 30]">
        <a-col>
          <ul>
            <li style="font-weight: bold">{{$t('商品销售明细')}}</li>
          </ul>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="22" :offset="1">
          <a-table :columns="columns5" :dataSource="dataSource5" :pagination="false" bordered></a-table>
        </a-col>
      </a-row>
      <a-row :gutter="[0, 30]">
        <a-col>
          <ul>
            <li style="font-weight: bold">{{$t('业务明细')}}</li>
          </ul>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="22" :offset="1">
          <a-table :columns="columns6" :dataSource="dataSource6" :pagination="false" bordered>
            <template slot="typeId" slot-scope="text, record">
              <span v-if="record.typeId != '8'">{{ text }}</span>
              <a v-else @click="viewDetail">{{ text }}</a>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </div>
    <check-out-print-modal ref="printModal"></check-out-print-modal>
    <share-detail-modal ref="sDtlModal"></share-detail-modal>
    <paytype-detail-modal ref="pDtlModal"></paytype-detail-modal>
  </j-modal>
</template>

<script>
import { getAction, downFile } from '@/api/manage'
import CheckOutPrintModal from './CheckOutPrintModal'
import ShareDetailModal from './ShareDetailModal'
import PaytypeDetailModal from './PaytypeDetailModal'
export default {
  name: 'CheckOutDetailtModal',
  components: {
    CheckOutPrintModal,
    ShareDetailModal,
    PaytypeDetailModal
  },
  data() {
    return {
      width: 800,
      visible: false,
      disableSubmit: false,
      model: {},
      columns5: [
        {
          title: this.$t('商品形态'),
          align: 'center',
          dataIndex: 'form_dictText',
          customRender:(t, r) =>{
            return {
              children: t,
              attrs: {
                rowSpan: r.form_dictTextRowSpan
              }
            }
          }
        },
        {
          title: this.$t('商品名称'),
          align: 'center',
          dataIndex: 'goodsName',
          customCell: (t,r) => {
            return {
              style :{
                maxWidth: '280px',
                whiteSpace: 'pre-wrap',
                wordBreak: 'break-all'
              }
            }
          }
        },
        {
          title: this.$t('数量'),
          align: 'center',
          dataIndex: 'saleAmount',
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('金额'),
          align: 'center',
          dataIndex: 'saleTotle',
          customRender: function (text) {
            return text.toFixed(2)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('兑换数量'),
          align: 'center',
          dataIndex: 'exchangeAmount',
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
      ],
      columns6: [],
      columns4: [],
      dataSource4: [],
      dataSource5: [],
      dataSource6: [],
      taxSetting: localStorage.getItem('taxSetting')
    }
  },
  methods: {
    viewPayDetail(record) {
      let dtl = { 
        id: this.model.id,
        dataType: this.model.dataType,
      }
      let list = [...this.dataSource4].slice(0, -1)
      this.$refs.pDtlModal.show(list, record, dtl, 2)
    },
    viewDetail() {
      let dtl = { 
        deviceId: this.model.deviceId,
        deviceType: this.model.deviceType,
        operator: this.model.operator,
        dataType: this.model.dataType,
        notCheckOut: 2
      }
      this.$refs.sDtlModal.show(dtl)
    },
    rowSpan(key) {
      let _list = this.dataSource5
      let _num = [] // 相同的数据先存储在一起
      let indexList = [] // 相同数据的下标数组

      for (let i = 0; i < _list.length; i++) {
        //  最后一条的 +1 时会为undefind 报错，所以需要给判断
        let downKey = _list[i + 1] ? _list[i + 1][key] : ''
        // 当与下一条数据不同时，添加当前数据到_num,并进行处理
        if (_list[i][key] != downKey) {
          _num.push(_list[i])
          indexList.push(i) //获取相同的 下标

          // 遍历相同数据的数组
          for (let z = 0; z < _num.length; z++) {
            // 第一个设置需要合并的数值
            _list[indexList[0]][`${key}RowSpan`] = _num.length
            if (z != 0) {
              //其他设置为0
              _list[indexList[z]][`${key}RowSpan`] = 0
            }
          }
          //  当与下一行不同时，切记清除数组，因为一列会有多个合并表格
          _num = []
          indexList = []
          continue
        } else {
          //当与下一条数据不同时，添加当前数据到_num,不进行处理
          _num.push(_list[i])
          indexList.push(i)
        }
      }
      // 重新渲染数据
      this.dataSource5 = _list
    },
    handleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = {}
      param.id = this.model.id
      downFile('/checkout/bisCheckOut/exportXlsDetail', param).then((data) => {
        if (!data) {
          this.$message.warning(this.$t('文件下载失败'))
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    edit(record) {
      this.taxSetting = localStorage.getItem('taxSetting')
      this.columns4 = [
        {
          title: this.$t('收款方式'),
          align: 'center',
          dataIndex: 'payType_dictText',
          scopedSlots: { customRender: 'payType_dictText' },
        },
        {
          title: this.$t('收款笔数'),
          align: 'center',
          dataIndex: 'count',
          customCell:function(){
            return{
              style:{
                textAlign:'right'
              }
            }
          }
        },
        {
          title: this.$t('应收金额'),
          align: 'center',
          dataIndex: 'shouldPay',
          customRender:function(text){
            return text.toFixed(2)
          },
          customCell:function(){
            return{
              style:{
                textAlign:'right'
              }
            }
          }
        },
        {
          title: this.$t('实收'),
          align: 'center',
          dataIndex: 'actualPay',
          customRender:function(text){
            return text.toFixed(2)
          },
          customCell:function(){
            return{
              style:{
                textAlign:'right'
              }
            }
          }
        },
        {
          title: this.$t('差额'),
          align: 'center',
          dataIndex: 'diff',
          customRender:function(text){
            return text.toFixed(2)
          },
          customCell:function(){
            return{
              style:{
                textAlign:'right'
              }
            }
          }
        },
      ]
      if (this.taxSetting != 0) {
        this.columns4.push({
          title: this.$t('其中税费'),
          align: 'center',
          dataIndex: 'taxPrice',
          customRender: function (text) {
            return text.toFixed(2)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        })
      }
      this.columns6 = [
        {
          title: this.$t('业务类型'),
          align: 'center',
          dataIndex: 'typeId_dictText',
          scopedSlots: { customRender: 'typeId' },
        },
        {
          title: this.$t('业务笔数'),
          align: 'center',
          dataIndex: 'count',
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('金额'),
          align: 'center',
          dataIndex: 'payAmount',
          customRender: function (text) {
            return text.toFixed(2)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        }
      ]
      if (localStorage.getItem('operateCoin') == 1) {
        this.columns6.splice(this.columns6.length, 0, {
          title: this.$t('代币'),
          align: 'center',
          dataIndex: 'coin',
          customRender: function (text) {
             return text.toFixed(2)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        })
      }
      if (localStorage.getItem('operateLottery') == 1) {
        this.columns6.splice(this.columns6.length, 0, {
          title: this.$t('彩票'),
          align: 'center',
          dataIndex: 'lottery',
          customRender: function (text) {
             return text.toFixed(0)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        })
      }
      if (localStorage.getItem('operateCredit') == 1) {
        this.columns6.splice(this.columns6.length, 0, {
          title: this.$t('积分'),
          align: 'center',
          dataIndex: 'integral',
          customRender: function (text) {
             return text.toFixed(0)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        })
      }
      if (localStorage.getItem('operateALottery') == 1) {
        this.columns6.splice(this.columns6.length, 0, {
          title: this.$t('A票'),
          align: 'center',
          dataIndex: 'alottery',
          customRender: function (text) {
             return text.toFixed(0)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        })
      }
      if (localStorage.getItem('operateACoin') == 1) {
        this.columns6.splice(this.columns6.length, 0, {
          title: this.$t('A币'),
          align: 'center',
          dataIndex: 'points',
          customRender: function (text) {
             return text.toFixed(0)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        })
      }
      this.dataSource4 = []
      this.dataSource5 = []
      this.dataSource6 = []
      this.visible = true
      this.model = Object.assign({}, record)
      getAction('/checkout/bisCheckOut/queryBisCheckOutGoodsByMainId', {
        id: this.model.id,
        groupBy: 'goods_id,goods_name,form',
        orderType: '2',
        dataType:this.model.dataType
      }).then((res) => {
        if (res.success) {
          this.dataSource5 = res.result
          if (this.dataSource5.length > 0) {
            this.addSumRow(['goodsName', 'saleAmount', 'saleTotle', 'exchangeAmount'], this.dataSource5)
            this.rowSpan('form_dictText');
          }
        }
      })
      getAction('/checkout/bisCheckOut/queryBisCheckOutTypeByMainId', {
        id: this.model.id,
        dataType:this.model.dataType
      }).then((res) => {
        if (res.success) {
          this.dataSource6 = res.result
          if (this.dataSource6.length > 0) {
            this.addSumRow(['typeId_dictText', 'count', 'payAmount', 'coin', 'lottery', 'integral', 'points', 'alottery'], this.dataSource6)
          }
        }
      })
      getAction('/checkout/bisCheckOut/queryBisCheckOutPayByMainId', { id: this.model.id, dataType:this.model.dataType }).then((res) => {
        if (res.success) {
          this.dataSource4 = res.result
          if(this.dataSource4.length>0){
            this.addSumRow(['payType_dictText', 'count', 'shouldPay','actualPay','diff', 'taxPrice'], this.dataSource4)
          }
        }
      })
    },
    addSumRow(myArr, dataSource) {
      let total = {}
      myArr.forEach((tcn, ind)=> {
        if (ind == 0) {
          total[tcn] = this.$t('合计')
        } else {
          total[tcn] = 0
        }
      })
      for (let key in total) {
        dataSource.forEach(function (ds) {
          if (!isNaN(total[key])) {
            total[key] += Number(ds[key])
          }
        })
      }
      dataSource.push(total)
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
    printReport(){
      this.$refs.printModal.show(this.model,2)
    }
  },
}
</script>